package com.lkd.http.controller;

import com.lkd.config.file.FileManager;
import com.lkd.entity.SkuEntity;
import com.lkd.exception.LogicException;
import com.lkd.service.ChannelService;
import com.lkd.service.SkuService;
import com.lkd.vo.Pager;
import com.lkd.vo.SkuVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@Slf4j
@RestController
public class SkuController {

    @Autowired
    private SkuService skuService;

    /**
     * 分页查询
     * @param pageIndex 页码
     * @param pageSize 页大小
     * @param classId 商品类别Id
     * @param skuName 商品名称
     * @return 分页结果
     */
    @GetMapping("/sku/search")
    public Pager<SkuEntity> search(@RequestParam(name = "pageIndex")Long pageIndex,
                                   @RequestParam(name = "pageSize")Long pageSize,
                                   @RequestParam(name = "classId",required = false)Long classId,
                                   @RequestParam(name = "skuName",required = false)String skuName){
        return skuService.search(pageIndex,pageSize,classId,skuName);
    }

    /**
     * 新增
     * @param sku
     * @return 是否成功
     */
    @PostMapping("/sku")
    public boolean add(@RequestBody SkuEntity sku) throws LogicException {
        return skuService.save(sku);
    }

    /**
     * 修改
     * @param sku
     * @return 是否成功
     */
    @PutMapping("/sku/{skuId}")
    public boolean update(@PathVariable(name = "skuId") Long skuId,
                          @RequestBody SkuEntity sku) throws LogicException {
        sku.setSkuId(skuId);

        return skuService.updateSku(sku);
    }

    @Autowired
    private FileManager fileManager;
    @PostMapping("/sku/fileUpload")
    public String fileUpload(@RequestParam(name = "fileName")MultipartFile file){
        try {
            String url = fileManager.uploadFile(file);
            return url;
        } catch (Exception e) {
            log.error("图片上传失败!");
            e.printStackTrace();
            throw new LogicException("图片上传失败!");
        }

    }


    /**
     * 根据售货机编号查询skulist
     * @param innerCode
     * @return
     */
    @GetMapping("/sku/getSkuListByInnerCode/{innerCode}")
    public List<SkuVO> getSkuListByInnerCode(@PathVariable(name = "innerCode")String innerCode){
        return skuService.getSkuListByInnerCode(innerCode);
    }


}
